<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      #btn {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        position: fixed;
        right: 30px;
        bottom: 30px;
        background-color: red;
        line-height: 100px;
        display: none;
      }
    </style>
  </head>

  <body style="height: 10000px">
    <div>顶部参照物</div>
    <div id="btn">返回按钮</div>
    <script>
      var btn = document.getElementById("btn");
      /*scroll：滚动条事件*/
      //1、绑定滚动条事件
      console.log(window);
      window.onscroll = function () {
        //2、获取滚动条的滚动距离  兼容写法 兼容谷歌和火狐浏览器
        var t = document.body.scrollTop || document.documentElement.scrollTop;
        console.log(t);
        //3、判断什么时候显示返回按钮
        if (t >= 500) {
          btn.style.display = "block";
        } else {
          btn.style.display = "none";
        }
      };
      // 4、点击返回顶部
      var time = null;
      btn.onclick = function () {
        var _top = 0; //保存滚动的数值
        time = setInterval(function () {
          _top -= 10;
          //2、获取滚动条的滚动距离  兼容写法 兼容谷歌和火狐浏览器
          var t = document.body.scrollTop || document.documentElement.scrollTop;
          //5、判断临界值
          if (t <= 0) {
            clearInterval(time);
            time = null;
            t = 0;
          }
          t += _top;
          //6、赋值
          document.body.scrollTop = t;
          document.documentElement.scrollTop = t;
        }, 30);
      };
    </script>
  </body>
</html>
